package com.xcdh.ittools.sql;

import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DSql {

    private String sql ;
    private List<String> condition ;

    private Map<String,Object> params ;

    public DSql(String sql){
        this.sql = sql ;
        this.condition = new ArrayList<>() ;
        this.params = new HashMap<>() ;
    }
    public DSql eq(String property , Object val){
        this.emptyNotSet(val,()->{
            this.condition.add(eq(property)) ;
        });
        params.put(property , val) ;
        return  this ;
    }

    public DSql in(String property , Object ...args){
        this.emptyNotSet(args,()->{
            this.condition.add(in(property)) ;
        });
        params.put(property , args) ;
        return  this ;
    }

    private String eq(String property){
        return String.format("%s %s=#{%s}" ,getPrefix() , property , property) ;
    }

    private String in(String property){
        return String.format("%s %s in (#{%s})" ,getPrefix() , property , property) ;
    }

    private String getPrefix(){
        return getPrefix(null) ;
    }
    private String getPrefix(String defPrefix){
        if(this.condition.size() == 0){
            return "where" ;
        }else{
           if(defPrefix != null){
               return defPrefix ;
           }
           return "and" ;
        }
    }

    public String getSql(){
        return String.format("%s %s",sql , String.join(" ",condition ));
    }
    public Map<String,Object> getParams(){
        return params ;
    }

    public void emptyNotSet(Object val , Runnable run){
        if(val instanceof String){
            if( !"".equals(val)){
                run.run();
            }
        }else {
            if(null != val){
                run.run();
            }
        }
    }
}
